<template>
    <div class="price-selector">
        <div class="time-selector card-container">
            <h3 class="section-title">时段选择</h3>
            <div class="time-slots-container">
                <div class="time-labels">
                    <div v-for="hour in 25" :key="`label-${hour - 1}`" class="time-label">
                        {{ hour - 1 }}
                    </div>
                </div>
                <div class="time-slots">
                    <div v-for="period in periods" :key="period.key" class="period-row">
                        <div class="period-label" :style="{ color: period.color }">{{ period.label }}</div>
                        <div class="hour-slots">
                            <div v-for="hour in 24" :key="`${period.key}-${hour - 1}`" :class="[
                                'hour-slot',
                                { 'selected': isHourSelected(period.key, hour - 1) }
                            ]" :style="{ backgroundColor: isHourSelected(period.key, hour - 1) ? period.color : '#f0f0f0' }"
                                @click="toggleHourSelection(period.key, hour - 1)"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="price-settings card-container">
            <h3 class="section-title">价格设置</h3>
            <div class="price-inputs">
                <div v-for="period in periods" :key="`price-${period.key}`" class="price-input-group">
                    <div class="price-label-container">
                        <div class="period-color-indicator" :style="{ backgroundColor: period.color }"></div>
                        <label :for="`${period.key}-price`">{{ period.label }}时电价：</label>
                    </div>
                    <div class="input-wrapper">
                        <el-input :id="`${period.key}-price`" v-model="priceInputs[period.key]" type="number" step="0.5"
                            placeholder="输入价格" @input="updatePrice(period.key)">
                            <template #append>元/kWh</template>
                        </el-input>
                    </div>
                </div>
            </div>
        </div>

        <div class="date-selector card-container">
            <h3 class="section-title">启用日期</h3>
            <el-date-picker v-model="selectedDate" type="date" placeholder="选择日期" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" class="date-picker" />
        </div>

        <div class="actions card-container">
            <el-button type="primary" @click="saveChanges" class="action-button save-button">保存</el-button>
            <el-button @click="resetToDefaults" class="action-button reset-button">重置</el-button>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';

const props = defineProps({
    // 初始价格数据
    initialPrices: {
        type: Object,
        default: () => ({
            sharp: '1.20000',
            peak: '0.81865',
            normal: '0.53257',
            valley: '0.24649'
        })
    },
    // 初始时段数据
    initialHours: {
        type: Object,
        default: () => ({
            sharpHours: [19, 20],
            peakHours: [8, 9, 10, 11, 16, 17, 18, 21],
            normalHours: [7, 12, 13, 14, 22, 23],
            valleyHours: [0, 1, 2, 3, 4, 5, 6, 15]
        })
    },
    // 移除isAdd属性，始终显示日期选择器
    // 初始日期
    initialDate: {
        type: String,
        default: () => {
            const today = new Date();
            return `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
        }
    }
});

const emit = defineEmits(['update-price-settings']);

// 选中的日期
const selectedDate = ref(props.initialDate);

// 时段定义
const periods = reactive([
    { key: 'sharp', label: '尖', color: '#FF5252' },
    { key: 'peak', label: '峰', color: '#FFC107' },
    { key: 'normal', label: '平', color: '#63C5DA' },
    { key: 'valley', label: '谷', color: '#4CAF50' }
]);

// 当前选中的小时
const selectedHours = reactive({
    sharp: [],
    peak: [],
    normal: [],
    valley: []
});

// 价格输入
const priceInputs = reactive({
    sharp: '',
    peak: '',
    normal: '',
    valley: ''
});

// 原始值备份 (用于重置)
const originalHours = ref({});
const originalPrices = ref({});
const originalDate = ref('');

// 初始化数据
const initializeData = () => {
    // 备份原始值
    originalHours.value = JSON.parse(JSON.stringify(props.initialHours));
    originalPrices.value = JSON.parse(JSON.stringify(props.initialPrices));
    originalDate.value = props.initialDate;

    // 设置当前选中的小时
    selectedHours.sharp = [...props.initialHours.sharpHours];
    selectedHours.peak = [...props.initialHours.peakHours];
    selectedHours.normal = [...props.initialHours.normalHours];
    selectedHours.valley = [...props.initialHours.valleyHours];

    // 设置价格输入
    priceInputs.sharp = props.initialPrices.sharp;
    priceInputs.peak = props.initialPrices.peak;
    priceInputs.normal = props.initialPrices.normal;
    priceInputs.valley = props.initialPrices.valley;

    // 设置日期
    selectedDate.value = props.initialDate;
};

// 检查小时是否被选中
const isHourSelected = (periodKey, hour) => {
    return selectedHours[periodKey].includes(hour);
};

// 切换小时选择 - 只能点击选择
const toggleHourSelection = (periodKey, hour) => {
    // 首先从所有时段中移除该小时
    Object.keys(selectedHours).forEach(key => {
        const index = selectedHours[key].indexOf(hour);
        if (index !== -1) {
            selectedHours[key].splice(index, 1);
        }
    });

    // 然后将小时添加到选中的时段
    selectedHours[periodKey].push(hour);

    // 排序以保持顺序
    selectedHours[periodKey].sort((a, b) => a - b);
};

// 更新价格
const updatePrice = (periodKey) => {
    // 可以在这里添加价格验证逻辑
    const price = parseFloat(priceInputs[periodKey]);
    if (isNaN(price) || price < 0) {
        // 处理无效价格
        return;
    }
};

// 保存更改
const saveChanges = () => {
    const updatedData = {
        prices: {
            sharp: priceInputs.sharp,
            peak: priceInputs.peak,
            normal: priceInputs.normal,
            valley: priceInputs.valley
        },
        hours: {
            sharpHours: [...selectedHours.sharp],
            peakHours: [...selectedHours.peak],
            normalHours: [...selectedHours.normal],
            valleyHours: [...selectedHours.valley]
        },
        // 始终添加日期信息
        date: selectedDate.value
    };

    // 触发更新事件
    emit('update-price-settings', updatedData);
};

// 重置为默认值
const resetToDefaults = () => {
    selectedHours.sharp = [...originalHours.value.sharpHours];
    selectedHours.peak = [...originalHours.value.peakHours];
    selectedHours.normal = [...originalHours.value.normalHours];
    selectedHours.valley = [...originalHours.value.valleyHours];

    priceInputs.sharp = originalPrices.value.sharp;
    priceInputs.peak = originalPrices.value.peak;
    priceInputs.normal = originalPrices.value.normal;
    priceInputs.valley = originalPrices.value.valley;

    selectedDate.value = originalDate.value;
};

// 组件挂载时初始化数据
onMounted(() => {
    initializeData();
});
</script>

<style scoped>
.price-selector {
    width: 100%;
    max-width: 1000px;
}

.card-container {
    padding: var(--gap-normal);
    margin-bottom: var(--gap-normal);
}

.section-title {
    margin-top: 0;
    margin-bottom: var(--gap-normal);
    color: #303133;
    font-size: var(--font-size-normal);
    font-weight: 600;
    position: relative;
    padding-left: var(--gap-small);
    border-left: 4px solid #409EFF;
}

/* 日期选择器样式 */
.date-selector {
    margin-bottom: var(--gap-large);
}

.date-picker {
    width: 100%;
    max-width: 300px;
}

.time-selector {
    margin-bottom: var(--gap-large);
}

.time-slots-container {
    position: relative;
    background-color: #fafafa;
    border-radius: 6px;
    padding: 8px 8px;
}

.time-labels {
    display: flex;
    margin-left: 80px;
    margin-bottom: var(--gap-small);
}

.time-label {
    flex: 1;
    text-align: center;
    font-size: 12px;
    color: #909399;
    font-weight: 500;
}

.time-slots {
    width: 100%;
}

.period-row {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
}

.period-label {
    width: 80px;
    text-align: center;
    font-weight: bold;
    font-size: 16px;
}

.hour-slots {
    display: flex;
    flex: 1;
}

.hour-slot {
    flex: 1;
    height: 35px;
    margin: 0 2px;
    background-color: #f0f0f0;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.hour-slot.selected {
    transform: scale(1.05);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.hour-slot:hover {
    opacity: 0.8;
    transform: scale(1.05);
}

.price-settings {
    margin-bottom: 24px;
}

.price-inputs {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 20px;
}

.price-input-group {
    display: flex;
    flex-direction: column;
    width: 100%;
}

.price-label-container {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
}

.period-color-indicator {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    margin-right: 8px;
}

.price-input-group label {
    font-weight: 500;
    color: #606266;
}

.input-wrapper {
    width: 100%;
}

.actions {
    display: flex;
    justify-content: flex-end;
    padding: 16px 20px;
}

.action-button {
    padding: 10px 25px;
    font-weight: 500;
    letter-spacing: 1px;
    transition: all 0.3s;
}

.save-button {
    background-color: #409EFF;
    margin-right: 15px;
}

.save-button:hover {
    background-color: #66b1ff;
    transform: translateY(-2px);
}

.reset-button:hover {
    transform: translateY(-2px);
}
</style>